
// Copyright (C) 2007 Richard Uhler
// This file is part of Esiply.
//
// Esiply is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License, Version 2,
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#include <assert.h>

#include <math.h>
#include <stdlib.h>
#include <limits>
#include "Completion.h"
#include "ErrorObject.h"
#include "EvalFunction.h"
#include "HostContext.h"
#include "HostValue.h"
#include "EsiplyObject.h"
#include "Null.h"
#include "Number.h"
#include "Object.h"
#include "Scope.h"
#include "String.h"
#include "Undefined.h"
#include "esiply.h"

std::string libpath;

HostContext esiply_init(const char* libdir)
{
    libpath = libdir ? libdir : JSLIBDIR;


    // Setup the global scope
    // Specifically don't retain here. The HostContext we return
    // will do that for us.
    Scope* global_scope = new Scope(NULL, Object::global, Object::global);
    HostContext hc(global_scope);

    // Initialize our implementation specific Esiply object. (not part
    // of the Ecma standard)
    esiply_object_init(global_scope);

    std::numeric_limits<double> limits;
    assert(limits.has_infinity);
    assert(limits.has_quiet_NaN);

    // Ecma 15.1.2.1 eval(x)
    Object::global->put(new String("eval"), new EvalFunction(), PA_DONT_ENUM);

    std::string path = esiply_getLibraryPath() + "Global.js";
    hc.run_file(path);

    // Object
    path = esiply_getLibraryPath() + "Object.js";
    hc.run_file(path);

    // Ecma 15.1.4.2 Function(...)
    path = esiply_getLibraryPath() + "Function.js";
    hc.run_file(path);

    // Ecma 15.1.4.3 Array(...)
    path = esiply_getLibraryPath() + "Array.js";
    hc.run_file(path);

    // Ecma 15.1.4.4 String(...)
    path = esiply_getLibraryPath() + "String.js";
    hc.run_file(path);

    // Ecma 15.1.4.5 Boolean(...)
    path = esiply_getLibraryPath() + "Boolean.js";
    hc.run_file(path);

    // Number
    path = esiply_getLibraryPath() + "Number.js";
    hc.run_file(path);

    // Ecma 15.1.4.? Math
    path = esiply_getLibraryPath() + "Math.js";
    hc.run_file(path);

    // Ecma 15.1.4.? Date
    path = esiply_getLibraryPath() + "Date.js";
    hc.run_file(path);

    // Ecma 15.1.4.? RegExp
    path = esiply_getLibraryPath() + "RegExp.js";
    hc.run_file(path);

    // Ecma 15.1.4.? Error(...)
    error_init(global_scope);

    // Return the HostContext.
    return hc;
}

std::string esiply_getLibraryPath()
{
    return libpath;
}

